import 'dart:io';

import 'package:flutter/material.dart';
import 'package:banner_view/banner_view.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/services.dart';
import 'package:gzmall_app/brands/brands_details_page.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/fwebView_scaffold.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/goods/goods_comment_page.dart';
import 'package:gzmall_app/goods/goods_skus_widget.dart';
import 'package:gzmall_app/model/comment.dart';
import 'package:gzmall_app/model/coupon.dart';
import 'package:gzmall_app/model/order_item.dart';
import 'package:gzmall_app/model/p_skus.dart';
import 'package:gzmall_app/model/picture.dart';
import 'package:gzmall_app/model/product.dart';
import 'package:gzmall_app/model/product_param.dart';
import 'package:gzmall_app/model/product_service.dart';
import 'package:gzmall_app/model/shopping_cart.dart';
import 'package:gzmall_app/model/user.dart';
import 'package:flutter/cupertino.dart';
import 'package:gzmall_app/shoppping_cart/confirm_order.dart';
import 'package:gzmall_app/store/store_detail_page.dart';
import 'package:gzmall_app/common/share_util.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:url_launcher/url_launcher.dart';

class GoodsDetailsPage extends StatefulWidget {
  int productId;

  GoodsDetailsPage({
    this.productId,
  });

  @override
  State<StatefulWidget> createState() =>
      GoodsDetailsPageState(productId: productId);
}

class GoodsDetailsPageState extends State<GoodsDetailsPage> {
  User _user = User.empty();

  double _topPadding;
  ScrollController _controller;
  Color _appBarBgColor;
  Color _appBarFontColor = Color.fromARGB(0, 0, 0, 0);

  int productId;
  Product _product;
  int _detailType = 1;
  PSkus _sSku;
  int _quantity = 1;

  String _selectSkuValueStr;

  SystemUiOverlayStyle _style = SystemUiOverlayStyle.dark;

  RefreshListView _refreshListView;

  GoodsDetailsPageState({
    this.productId,
  });

  void init() {
    _topPadding = MediaQuery.of(context).padding.top;
    _controller = ScrollController();
    _controller.addListener(() {
      if (!mounted) return;
      setState(() {
        double scale = 0.0;
        if (_controller.offset > 0) {
          scale = _controller.offset / 70.0;
        }
        if (scale > 1) scale = 1.0;
        int transparency = (255.0 * scale).toInt();
        _appBarBgColor = Color.fromARGB(transparency, 255, 255, 255);
        _appBarFontColor = Color.fromARGB(transparency, 0, 0, 0);
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _getUserInfoFromLocate();
  }

  @override
  void dispose() {
    _style = SystemUiOverlayStyle.light;
    SystemChrome.setSystemUIOverlayStyle(_style);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(_style);
    init();
    if (_product != null) {
      _refreshListView = RefreshListView(
          onRefresh: _onRefresh, child: _createMainContentView());
    }
    return Theme(
        data: Theme.of(context).copyWith(
          canvasColor: Colors.transparent,
        ),
        child: Scaffold(
          body: Container(
            color: Colors.white,
            child: Stack(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    Expanded(
                      child: _product == null
                          ? Center(
                              child: Text("加载中..."),
                            )
                          : _refreshListView,
                    ),
                    Container(
                      color: Colors.white,
                      height: 70.0,
                      padding: const EdgeInsets.all(10.0),
                      alignment: Alignment.center,
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Container(
                              margin: const EdgeInsets.only(left: 10.0),
                              child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    _getIconTextButton(
                                        "收藏",
                                        Image.asset(
                                          "images/collect.png",
                                          width: 20.0,
                                          height: 20.0,
                                        ), () {
                                      if (productId != null && productId > 0) {
                                        _favorites(productId);
                                      }
                                    }),
                                    _getIconTextButton(
                                        "店铺",
                                        Image.asset(
                                          "images/store.png",
                                          width: 20.0,
                                          height: 20.0,
                                        ), () {
                                      Navigator.of(context).push(
                                          new MaterialPageRoute(builder: (_) {
                                        return new StoreDetailPage(
                                            store: _product.shop);
                                      }));
                                    }),
                                    _getIconTextButton(
                                        "客服",
                                        Image.asset(
                                          "images/service.png",
                                          width: 20.0,
                                          height: 20.0,
                                        ), () {
                                      // User.isLogin().then((v) {
                                      //   if (v) {
                                      //     if (_product != null &&
                                      //         _product.serviceUrl != null &&
                                      //         _product.serviceUrl.isNotEmpty) {
                                      //       Navigator.of(context).push(
                                      //           new MaterialPageRoute(
                                      //               builder: (_) {
                                      //         return FWebviewScaffold(
                                      //           url: _product.serviceUrl,
                                      //           userAgent:
                                      //               Api.kWebViewUserAgent,
                                      //           enableMessaging: true,
                                      //           withJavascript: true,
                                      //           clearCache: true,
                                      //           appBar: AppBar(
                                      //             title: Text(
                                      //                 (_product?.shop?.name ??
                                      //                         "") +
                                      //                     "客服"),
                                      //           ),
                                      //         );
                                      //       }));
                                      //       return;
                                      //     }
                                      //   } else {
                                      //     Navigator.of(context)
                                      //         .pushNamed('/login_page')
                                      //         .then((v) {});
                                      //   }
                                      // });
                                      if (_product?.shop?.phone != null) {
                                        _makePhoneCall(
                                            'tel:${_product?.shop?.phone}');
                                      } else {
                                        ToastUtil.showMessageToast('商家电话错误');
                                      }
                                    }),
                                  ]),
                            ),
                          ),
                          Container(
                            margin:
                                const EdgeInsets.only(left: 15.0, right: 5.0),
                            child: Row(children: <Widget>[
                              Builder(
                                builder: (BuildContext context) =>
                                    GestureDetector(
                                      onTap: () {
                                        // if (_sSku != null) {
                                        //   _addShopCart(_sSku.id, _quantity);
                                        // } else {
                                        //   _showSelectSkuSheet(context);
                                        // }
                                        _showSelectSkuSheet(context);
                                      },
                                      child: Container(
                                        height: 50.0,
                                        width: 100.0,
                                        alignment: Alignment.center,
                                        decoration: new BoxDecoration(
                                            color: Colors.orange,
                                            borderRadius: new BorderRadius.only(
                                                topLeft: Radius.circular(100.0),
                                                bottomLeft:
                                                    Radius.circular(100.0),
                                                topRight: Radius.circular(0.0),
                                                bottomRight:
                                                    Radius.circular(0.0))),
                                        child: new Text(
                                          "购物车",
                                          style: TextStyle(
                                              fontSize: 15.0,
                                              color: Colors.white),
                                        ),
                                      ),
                                    ),
                              ),
                              Builder(
                                builder: (BuildContext context) =>
                                    GestureDetector(
                                      onTap: () {
                                        // if (_sSku != null) {
                                        //   OrderItem orderItem = OrderItem(
                                        //       0,
                                        //       _quantity,
                                        //       _product.name,
                                        //       _selectSkuValueStr,
                                        //       _product.promotion
                                        //           ? _sSku.promotionPrice
                                        //           : _sSku.salePrice,
                                        //       _sSku.skuImages,
                                        //       _sSku.id,
                                        //       "",
                                        //       "",
                                        //       _sSku.avatar);
                                        //   List<OrderItem> orderItems = [];
                                        //   orderItems.add(orderItem);
                                        //   ShoppingCart cart = ShoppingCart(
                                        //       _product.shop != null
                                        //           ? _product.shop.name
                                        //           : "",
                                        //       orderItems);
                                        //   List<ShoppingCart> shoppingCartList =
                                        //       [];
                                        //   shoppingCartList.add(cart);

                                        //   Navigator.of(context).push(
                                        //       new MaterialPageRoute(
                                        //           builder: (_) {
                                        //     return ConfirmOrderPage(
                                        //       shoppingCartList:
                                        //           shoppingCartList,
                                        //       skuId: _sSku.id,
                                        //       quantity: _quantity,
                                        //     );
                                        //   }));
                                        // } else {
                                        //   _showSelectSkuSheet(context);
                                        // }
                                        _showSelectSkuSheet(context);
                                      },
                                      child: Container(
                                        height: 50.0,
                                        width: 100.0,
                                        alignment: Alignment.center,
                                        decoration: new BoxDecoration(
                                            color: Colors.red,
                                            borderRadius: new BorderRadius.only(
                                                topLeft: Radius.circular(0.0),
                                                bottomLeft:
                                                    Radius.circular(0.0),
                                                topRight:
                                                    Radius.circular(100.0),
                                                bottomRight:
                                                    Radius.circular(100.0))),
                                        child: new Text(
                                          "立即购买",
                                          style: TextStyle(
                                              fontSize: 15.0,
                                              color: Colors.white),
                                        ),
                                      ),
                                    ),
                              ),
                            ]),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                _createAppBarRow(),
              ],
            ),
          ),
        ));
  }

  _createAppBarRow() {
    return Container(
      color: _appBarBgColor,
      padding: EdgeInsets.fromLTRB(10.0, _topPadding + 10.0, 10.0, 10.0),
      child: Row(
        children: <Widget>[
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Image.asset(
              "images/p_back.png",
              width: 28.0,
              height: 28.0,
            ),
          ),
          Expanded(
            child: Container(
              padding: const EdgeInsets.only(left: 10.0),
              child: Text(
                _product != null ? _product.name : "",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: _appBarFontColor, fontSize: 22.0),
              ),
            ),
          ),
          LaunchUtil.isInstallWeixin && !SettingUtil.isAppStoreAudit()
              ? InkWell(
                  onTap: () {
                    ShareUtil.showShareSelect(
                        context,
                        _product.shareUrl,
                        _product.shareTitle,
                        _product.shareContent,
                        _product.shareAvatar,
                        _product.shareTitle);
                  },
                  child: Image.asset(
                    "images/p_share.png",
                    width: 28.0,
                    height: 28.0,
                  ),
                )
              : Container(
                  width: 28.0,
                  height: 28.0,
                ),
        ],
      ),
    );
  }

  _createBannerView(List<Picture> images) {
    return images != null && images.length > 0
        ? Container(
            alignment: Alignment.center,
            height: 280.0,
            child: BannerView(
              _getBannerImage(images),
              log: false,
              indicatorMargin: 10.0,
              indicatorNormal: _indicatorItem(ColorCommon.grey7),
              indicatorSelected:
                  _indicatorItem(ColorCommon.primaryColor, selected: true),
              indicatorBuilder: (context, indicator) {
                return _indicatorContainer(indicator);
              },
              intervalDuration: Duration(seconds: 3),
              animationDuration: Duration(milliseconds: 500),
            ),
          )
        : Container(height: 280.0);
  }

  List<Widget> _getBannerImage(List<Picture> images) {
    return images.map((e) {
      return GestureDetector(
        onTap: () {},
        child: CachedNetworkImage(
          imageUrl: e.url,
          fit: BoxFit.fill,
        ),
      );
    }).toList();
  }

  Widget _indicatorContainer(Widget indicator) {
    var container = Container(
      height: 30.0,
      child: Stack(
        children: <Widget>[
          Container(
            color: Colors.transparent,
          ),
          Align(
            alignment: Alignment.center,
            child: indicator,
          ),
        ],
      ),
    );

    return Align(
      alignment: Alignment.bottomCenter,
      child: container,
    );
  }

  Widget _indicatorItem(Color color, {bool selected = false}) {
    double width = selected ? 18.0 : 6.0;
    return Container(
      width: width,
      height: 4.0,
      decoration: BoxDecoration(
        color: color,
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.all(
          Radius.circular(5.0),
        ),
      ),
    );
  }

  _createMainContentView() {
    _selectSkuValueStr = "已选:";
    if (_sSku != null &&
        _sSku.optionValues != null &&
        _sSku.optionValues.length > 0) {
      for (var item in _sSku.optionValues) {
        _selectSkuValueStr =
            _selectSkuValueStr + "\"" + item.presentation + "\" ";
      }
    }

    Comment _comment = null;
    if (_product != null &&
        _product.comments != null &&
        _product.comments.length > 0) {
      _comment = _product.comments[0];
    }
    String reviewStr = "";
    if (_comment != null && _comment.review != null) {
      switch (_comment.review) {
        case "well":
          reviewStr = "好评";
          break;
        case "normal":
          reviewStr = "中评";
          break;
        case "bad":
          reviewStr = "差评";
          break;
        default:
      }
    }

    return ListView(
      controller: _controller,
      padding: const EdgeInsets.only(top: 0.0),
      children: <Widget>[
        _createBannerView(_product.pictures),
        Container(
          color: ColorCommon.grey5,
          margin: const EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
          padding: const EdgeInsets.all(10.0),
          child: Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10.0),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(bottom: 8.0),
                    child: Row(
                      children: <Widget>[
                        Text(
                          "¥" +
                              (_product.promotion
                                  ? (_sSku != null
                                      ? (_sSku.promotionPrice ?? "0.0")
                                      : (_product.lowPromotionPrice ?? "0.0"))
                                  : (_sSku != null
                                      ? (_sSku.salePrice ?? "0.0")
                                      : (_product.lowSalePrice ?? "0.0"))),
                          style: TextStyle(
                              fontSize: 25.0, color: ColorCommon.primaryColor),
                        ),
                        _product.promotion != null && _product.promotion
                            ? _getTagView(
                                "促销价",
                                Colors.white,
                                ColorCommon.primaryColor,
                                ColorCommon.primaryColor)
                            : Container(),
                      ],
                    ),
                  ),
                  _product.promotion != null && _product.promotion
                      ? Padding(
                          padding: const EdgeInsets.only(bottom: 8.0),
                          child: Row(
                            children: <Widget>[
                              Text(
                                "销售价",
                                style: TextStyle(
                                    fontSize: 13.0, color: ColorCommon.grey8),
                              ),
                              Text(
                                "¥" +
                                    (_sSku != null
                                        ? (_sSku.salePrice ?? "0.0")
                                        : (_product.lowSalePrice ?? "0.0")),
                                style: TextStyle(
                                    fontSize: 13.0,
                                    color: ColorCommon.grey8,
                                    decoration: TextDecoration.lineThrough,
                                    decorationStyle: TextDecorationStyle.solid),
                              ),
                            ],
                          ),
                        )
                      : Container(),
                  Stack(
                    children: <Widget>[
                      _product.directSale != null && _product.directSale
                          ? _getTagView(
                              "自营",
                              Colors.white,
                              ColorCommon.primaryColor,
                              ColorCommon.primaryColor)
                          : Container(),
                      Text(
                        _product.directSale != null && _product.directSale
                            ? ("            " + _product.name)
                            : _product.name,
                        textAlign: TextAlign.start,
                        style: TextStyle(
                            fontSize: 17.0,
                            color: ColorCommon.black1,
                            fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 10.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          "运费: " +
                              (_product.expressFee != null &&
                                      double.parse(_product.expressFee) > 0
                                  ? "¥${_product.expressFee}"
                                  : "免运费"),
                          style: TextStyle(
                              fontSize: 12.0, color: ColorCommon.grey8),
                        ),
                        Text(
                          "月销" + _product.salesVolume.toString() + "件",
                          style: TextStyle(
                              fontSize: 12.0, color: ColorCommon.grey8),
                        ),
                        Text(
                          _product?.shop?.area ?? "",
                          style: TextStyle(
                              fontSize: 12.0, color: ColorCommon.grey8),
                        ),
                      ],
                    ),
                  ),
                ]),
          ),
        ),
        Container(
          color: ColorCommon.grey5,
          margin: const EdgeInsets.only(left: 10.0, right: 10.0),
          padding: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
          child: Column(
            children: <Widget>[
              _product != null &&
                      _product.coupons != null &&
                      _product.coupons.length > 0
                  ? Container(
                      color: Colors.white,
                      padding: const EdgeInsets.only(
                          left: 15.0, right: 10.0, top: 10.0, bottom: 10.0),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            "优惠",
                            style: TextStyle(
                                fontSize: 17.0, color: ColorCommon.grey8),
                          ),
                          Expanded(
                            child: Container(
                              margin: const EdgeInsets.only(
                                  left: 10.0, right: 10.0),
                              child: Column(
                                children: <Widget>[
                                  Row(
                                    children: <Widget>[
                                      _getTagView(
                                          "店铺优惠券",
                                          ColorCommon.red3,
                                          ColorCommon.red3,
                                          ColorCommon.primaryColor),
                                      Padding(
                                        padding:
                                            const EdgeInsets.only(left: 10.0),
                                        child: _getTagView(
                                            _product.coupons[0].name ?? "",
                                            Colors.white,
                                            ColorCommon.primaryColor,
                                            ColorCommon.primaryColor),
                                      ),
                                    ],
                                  ),
                                  // Padding(
                                  //   padding: const EdgeInsets.only(top: 4.0),
                                  //   child: Row(
                                  //     children: <Widget>[
                                  //       _getTagView("积分", ColorCommon.red3,
                                  //           ColorCommon.red3, ColorCommon.primaryColor),
                                  //       Padding(
                                  //         padding: const EdgeInsets.only(left: 10.0),
                                  //         child: Text(
                                  //           "购买可得35积分",
                                  //           style: TextStyle(
                                  //               fontSize: 13.0,
                                  //               color: ColorCommon.grey8),
                                  //         ),
                                  //       ),
                                  //     ],
                                  //   ),
                                  // ),
                                ],
                              ),
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              _showProductCoupons(context, _product.coupons);
                            },
                            child: Row(
                              children: <Widget>[
                                Text(
                                  "领券",
                                  style: TextStyle(
                                      fontSize: 13.0, color: ColorCommon.grey8),
                                ),
                                new Image.asset(
                                  "images/right_arrow.png",
                                  width: 10.0,
                                  height: 10.0,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    )
                  : Container(),
              _createServiceView(),
            ],
          ),
        ),
        Container(
          color: ColorCommon.grey5,
          margin: const EdgeInsets.only(left: 10.0, right: 10.0),
          padding: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
          child: Column(children: <Widget>[
            Builder(
              builder: (BuildContext context) => GestureDetector(
                    onTap: () {
                      _showSelectSkuSheet(context);
                    },
                    child: Container(
                      color: Colors.white,
                      margin: const EdgeInsets.only(bottom: 1.0),
                      padding: const EdgeInsets.only(
                          left: 15.0, right: 10.0, top: 15.0, bottom: 15.0),
                      child: Row(
                        children: <Widget>[
                          Text(
                            "选择",
                            style: TextStyle(
                                fontSize: 17.0, color: ColorCommon.grey8),
                          ),
                          Expanded(
                            child: Padding(
                              padding: const EdgeInsets.only(left: 20.0),
                              child: Text(
                                _sSku != null ? _selectSkuValueStr : "请选择 规格",
                                style: TextStyle(
                                    fontSize: 15.0, color: ColorCommon.black2),
                              ),
                            ),
                          ),
                          new Image.asset(
                            "images/right_arrow.png",
                            width: 10.0,
                            height: 10.0,
                          ),
                        ],
                      ),
                    ),
                  ),
            ),
            Builder(
              builder: (BuildContext context) => GestureDetector(
                    onTap: () {
                      _showProductParameters(context, _product.parameters);
                    },
                    child: Container(
                      color: Colors.white,
                      margin: const EdgeInsets.only(bottom: 1.0),
                      padding: const EdgeInsets.only(
                          left: 15.0, right: 10.0, top: 15.0, bottom: 15.0),
                      child: Row(
                        children: <Widget>[
                          Text(
                            "产品参数",
                            style: TextStyle(
                                fontSize: 17.0, color: ColorCommon.grey8),
                          ),
                          Expanded(
                            child: Container(),
                          ),
                          new Image.asset(
                            "images/right_arrow.png",
                            width: 10.0,
                            height: 10.0,
                          ),
                        ],
                      ),
                    ),
                  ),
            ),
          ]),
        ),
        Container(
          color: ColorCommon.grey5,
          margin: const EdgeInsets.only(left: 10.0, right: 10.0),
          padding: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
          child: Row(
            children: <Widget>[
              Text(
                "宝贝评价",
                style: TextStyle(fontSize: 18.0, color: ColorCommon.black2),
              ),
              Expanded(
                child: Container(),
                // child: Padding(
                //   padding: const EdgeInsets.only(left: 4.0),
                //   child: Text(
                //     "好评率98.7%",
                //     style: TextStyle(fontSize: 13.0, color: ColorCommon.grey8),
                //   ),
                // ),
              ),
              InkWell(
                onTap: () {
                  Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                    return GoodsCommentPage(_product.id);
                  }));
                },
                child: Text(
                  "查看全部",
                  style: TextStyle(
                      fontSize: 15.0, color: ColorCommon.primaryColor),
                ),
              ),
            ],
          ),
        ),
        _comment != null
            ? Container(
                color: ColorCommon.grey5,
                margin: const EdgeInsets.only(left: 10.0, right: 10.0),
                padding: const EdgeInsets.only(
                    left: 10.0, right: 10.0, bottom: 10.0),
                child: Container(
                  color: Colors.white,
                  padding: const EdgeInsets.all(15.0),
                  margin: const EdgeInsets.only(bottom: 1.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          new Container(
                            width: 30.0,
                            height: 30.0,
                            margin: const EdgeInsets.only(right: 15.0),
                            decoration: new BoxDecoration(
                              color: Colors.grey,
                              borderRadius: new BorderRadius.circular(100.0),
                              image: new DecorationImage(
                                  image: new CachedNetworkImageProvider(
                                      _comment.user != null &&
                                              _comment.user.avatar != null
                                          ? _comment.user.avatar
                                          : Api.defaultAvatar),
                                  fit: BoxFit.fill),
                            ),
                          ),
                          Text(
                            _comment.user != null &&
                                    _comment.user.nickname != null
                                ? _comment.user.nickname
                                : "",
                            style: TextStyle(
                                fontSize: 15.0, color: ColorCommon.grey8),
                          ),
                        ],
                      ),
                      reviewStr != null && reviewStr.isNotEmpty
                          ? Container(
                              margin: const EdgeInsets.only(
                                  top: 10.0, bottom: 10.0),
                              child: Wrap(
                                spacing: 10.0,
                                children: <Widget>[
                                  _getTagView(reviewStr, ColorCommon.red3,
                                      ColorCommon.red3, ColorCommon.grey8),
                                  // _getTagView("快递很快", ColorCommon.red3,
                                  //     ColorCommon.red3, ColorCommon.grey8),
                                  // _getTagView("很便宜", ColorCommon.red3,
                                  //     ColorCommon.red3, ColorCommon.grey8),
                                ],
                              ),
                            )
                          : Container(),
                      Text(
                        _comment.content ?? "",
                        style:
                            TextStyle(fontSize: 10.0, color: ColorCommon.grey8),
                      ),
                    ],
                  ),
                ),
              )
            : Container(),
        _createBrandView(),
        _createDetailTabView(),
        _detailType == 1
            ? _createProductDetailView(_product.details)
            : _createQAView(),
      ],
    );
  }

  _createServiceView() {
    if (_product.serviceItems != null && _product.serviceItems.length > 0) {
      List<Widget> serviceWidgets = [];
      int index = 0;
      for (var item in _product.serviceItems) {
        if (index < 2) {
          index == 0
              ? serviceWidgets.add(Expanded(
                  child: _getServieTag(item),
                ))
              : serviceWidgets.add(_getServieTag(item));
          index++;
        } else {
          break;
        }
      }
      serviceWidgets.add(
        new Image.asset(
          "images/right_arrow.png",
          width: 10.0,
          height: 10.0,
        ),
      );
      return Builder(
        builder: (BuildContext context) => GestureDetector(
              onTap: () {
                _showProductServices(context, _product.serviceItems);
              },
              child: Container(
                margin: const EdgeInsets.only(top: 1.0),
                padding: const EdgeInsets.all(10.0),
                color: Colors.white,
                child: Row(children: serviceWidgets),
              ),
            ),
      );
    } else {
      return Container();
    }
  }

  _getServieTag(ProductService service) {
    return Row(
      children: <Widget>[
        CachedNetworkImage(
          imageUrl: service.avatar,
          width: 20.0,
          height: 20.0,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 8.0),
          child: Text(
            service.name,
            style: TextStyle(fontSize: 15.0, color: ColorCommon.grey3),
          ),
        ),
      ],
    );
  }

  _createBrandView() {
    if (_product.brand != null) {
      return Container(
        color: ColorCommon.grey5,
        margin: const EdgeInsets.only(left: 10.0, right: 10.0),
        child: InkWell(
          onTap: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (_) {
              return BrandsDetailsPage(id: _product.brand.id);
            }));
          },
          child: Container(
            padding: const EdgeInsets.all(10.0),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: ColorCommon.grey3)),
            margin:
                const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
            child: Row(children: <Widget>[
              _product?.brand?.avatar != null &&
                      _product.brand.avatar.isNotEmpty
                  ? CachedNetworkImage(
                      imageUrl: _product.brand.avatar,
                      fit: BoxFit.fill,
                      width: 45.0,
                      height: 45.0,
                    )
                  : Container(
                      width: 45.0,
                      height: 45.0,
                      color: Colors.grey,
                    ),
              Expanded(
                child: Container(
                  margin: const EdgeInsets.only(left: 20.0, right: 10.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        _product.brand.name,
                        style: TextStyle(
                            fontSize: 14.0, color: ColorCommon.black1),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 5.0),
                        child: Text(
                          "在售商品80件",
                          style: TextStyle(
                              fontSize: 14.0, color: ColorCommon.black1),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Text(
                "进入品牌",
                style:
                    TextStyle(fontSize: 14.0, color: ColorCommon.primaryColor),
              ),
              new Image.asset(
                "images/right_arrow.png",
                width: 10.0,
                height: 10.0,
              ),
            ]),
          ),
        ),
      );
    } else {
      return Container();
    }
  }

  _createProductDetailView(List<Picture> images) {
    return Container(
      color: ColorCommon.grey5,
      margin: const EdgeInsets.only(left: 10.0, right: 10.0),
      padding: const EdgeInsets.only(
          left: 10.0, right: 10.0, top: 10.0, bottom: 10.0),
      child: Column(
          children: images.map((picture) {
        return CachedNetworkImage(
          imageUrl: picture.url,
          fit: BoxFit.fill,
        );
      }).toList()),
    );
  }

  _createDetailTabView() {
    return Container(
      color: ColorCommon.grey5,
      margin: const EdgeInsets.only(left: 10.0, right: 10.0),
      padding: const EdgeInsets.only(left: 10.0, right: 10.0),
      child: Row(
        children: <Widget>[
          _getDetailTabView("图文详情", 1),
          // _getDetailTabView("问题回答", 2),
        ],
      ),
    );
  }

  _getDetailTabView(String text, int detailType) {
    return Expanded(
      child: InkWell(
        onTap: () {
          if (!mounted) return;
          setState(() {
            _detailType = detailType;
          });
        },
        child: Container(
          alignment: Alignment.center,
          height: 60.0,
          decoration: BoxDecoration(
              color: _detailType == detailType ? Colors.black : Colors.white,
              border: Border.all(color: Colors.black)),
          child: Text(
            text,
            style: TextStyle(
              fontSize: 13.0,
              color: _detailType == detailType ? Colors.white : Colors.black,
            ),
          ),
        ),
      ),
    );
  }

  _createQAView() {
    return Container(
      color: ColorCommon.grey5,
      margin: const EdgeInsets.only(left: 10.0, right: 10.0),
      padding: const EdgeInsets.only(
          left: 10.0, right: 10.0, top: 10.0, bottom: 10.0),
    );
  }

  Widget _getIconTextButton(String text, Widget iconWidget, Function onTap) {
    return InkWell(
        onTap: onTap,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            iconWidget,
            Container(
              alignment: Alignment.bottomCenter,
              height: 18.0,
              child: Text(
                text,
                style: TextStyle(fontSize: 12.0),
              ),
            ),
          ],
        ));
  }

  Widget _getTagView(
      String text, Color bgColor, Color borderColor, Color textColor,
      {DecorationImage image}) {
    BoxDecoration decoration;
    if (image == null) {
      decoration = BoxDecoration(
          color: bgColor,
          border: Border.all(color: borderColor),
          borderRadius: BorderRadius.all(Radius.circular(100.0)));
    } else {
      decoration = BoxDecoration(image: image);
    }
    return Container(
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      decoration: decoration,
      child: Text(
        text,
        style: TextStyle(fontSize: 13.0, color: textColor),
      ),
    );
  }

  _showSelectSkuSheet(BuildContext context) {
    showBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return GoodsSkusWidget(
            _product.optionType,
            _product.skus,
            _onSelectSku,
            _product.name,
            _product.shop != null ? _product.shop.name : "",
            _product.stock,
            _sSku,
            _quantity);
      },
    );
  }

  _onSelectSku(PSkus sSku, int quantity) {
    new Future.delayed(Duration.zero, () {
      if (!mounted) return;
      setState(() {
        _sSku = sSku;
        _quantity = quantity;
      });
    });
  }

  _showProductParameters(BuildContext context, List<ProductParam> params) {
    List<Widget> ws;
    if (params != null && params.length > 0) {
      ws = params.map((item) => _getProductParameterItem(item)).toList();
    } else {
      ws = [];
      ws.add(Align(
          alignment: Alignment.topLeft,
          child: Text(
            "无",
            style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
          )));
    }
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 15.0),
                child: Text(
                  "产品参数",
                  style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  children: ws,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  _showProductServices(BuildContext context, List<ProductService> services) {
    List<Widget> ws;
    if (services != null && services.length > 0) {
      ws = services.map((item) => _getProductServiceItem(item)).toList();
    } else {
      ws = [];
      ws.add(Align(
          alignment: Alignment.topLeft,
          child: Text(
            "无",
            style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
          )));
    }
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 15.0),
                child: Text(
                  "基础服务",
                  style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  children: ws,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  _showProductCoupons(BuildContext context, List<Coupon> coupons) {
    List<Widget> ws;
    if (coupons != null && coupons.length > 0) {
      ws = coupons.map((item) => _getProductCouponItem(item)).toList();
    } else {
      ws = [];
      ws.add(Align(
          alignment: Alignment.topLeft,
          child: Text(
            "无",
            style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
          )));
    }
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 15.0),
                child: Text(
                  "领优惠券",
                  style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  children: ws,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _getProductServiceItem(ProductService service) {
    return Container(
        margin: const EdgeInsets.all(10.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            CachedNetworkImage(
              imageUrl: service.avatar,
              width: 20.0,
              height: 20.0,
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(left: 10.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      service.name,
                      style:
                          TextStyle(fontSize: 18.0, color: ColorCommon.grey3),
                    ),
                    Text(
                      service.description,
                      style:
                          TextStyle(fontSize: 15.0, color: ColorCommon.grey3),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ));
  }

  Widget _getProductParameterItem(ProductParam param) {
    return Container(
      margin: const EdgeInsets.all(10.0),
      child: Row(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(right: 15.0),
            child: Text(
              param.key,
              style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
            ),
          ),
          Expanded(
            child: Text(
              param.value,
              style: TextStyle(fontSize: 18.0, color: ColorCommon.grey8),
            ),
          ),
        ],
      ),
    );
  }

  Widget _getProductCouponItem(Coupon coupon) {
    return Container(
        margin: const EdgeInsets.only(top: 5.0, bottom: 5.0),
        padding: const EdgeInsets.all(10.0),
        decoration: BoxDecoration(
            color: Colors.yellow,
            borderRadius: BorderRadius.all(Radius.circular(5.0))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "¥",
                      style: TextStyle(color: Colors.orange, fontSize: 12.0),
                    ),
                    Text(
                      coupon.money ?? "",
                      style: TextStyle(color: Colors.orange, fontSize: 18.0),
                    ),
                    Text(
                      coupon.name ?? "",
                      style: TextStyle(color: Colors.orange, fontSize: 12.0),
                    ),
                  ],
                ),
                Text(
                  coupon.remark ?? "",
                  style: TextStyle(color: Colors.orange, fontSize: 12.0),
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text("有效期: ",
                        style: TextStyle(color: Colors.orange, fontSize: 12.0)),
                    Text(
                        (coupon.startAt ?? "") +
                            (" 至\n") +
                            (coupon.endAt ?? ""),
                        style: TextStyle(color: Colors.orange, fontSize: 12.0)),
                  ],
                ),
              ],
            )),
            InkWell(
              onTap: () {
                _receiveCoupon(coupon.id);
              },
              child: Text(
                "立即领取",
                style: TextStyle(color: Colors.orange, fontSize: 16.0),
              ),
            ),
          ],
        ));
  }

  void _onRefresh(bool up) {
    if (up) {
      _getUserInfoFromLocate();
    }
  }

  _getUserInfoFromLocate() async {
    await _user.getUserInfo();
    _getProductInfo(productId);
  }

  _getProductInfo(int id) {
    Map<String, String> params;
    if (_user != null && _user.id > 0) {
      params = {
        "user_id": _user.id.toString(),
      };
    }

    NetUtil.get(
        context,
        Api.spus + '/' + id.toString(),
        (data, message) {
          if (!mounted) return;
          setState(() {
            _product = Product.fromJson(data);

            _addTracks(_product.id);
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(true);
          }
        },
        params: params,
        errorCallBack: (e) {
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(true);
          }
        });
  }

  _addShopCart(int skuId, int quantity) {
    Map<String, String> params = {
      "sku_id": skuId.toString(),
      "quantity": quantity.toString(),
    };

    NetUtil.post(context, Api.orderItems, (data, message) {
      ToastUtil.showMessageToast(message);
    }, params: params, isShowLoading: true);
  }

  _favorites(int id) {
    Map<String, String> params = {
      "type": "Spu",
      "id": id.toString(),
    };

    NetUtil.post(context, Api.favorites, (data, message) {
      ToastUtil.showMessageToast(message);
    }, params: params, isShowLoading: true);
  }

  _addTracks(int id) {
    Map<String, String> params = {
      "spu_id": id.toString(),
    };

    NetUtil.post(context, Api.spuTracks, (data, message) {},
        params: params, isInterceptError: false, isShowLoading: true);
  }

  _receiveCoupon(int id) {
    Map<String, String> params = {
      "coupon_id": id.toString(),
    };

    NetUtil.post(context, Api.userCoupons, (data, message) {
      ToastUtil.showMessageToast(message);
    }, params: params, isShowLoading: true);
  }

  Future<void> _makePhoneCall(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      ToastUtil.showMessageToast('无法拨打电话');
    }
  }
}
